/* eslint-disable indent */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
        <!-- 卡片头部 -->
      <el-row :gutter="20">
        <!--搜索 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select" clearable @clear="getUserList" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="5">
          <el-button type="primary" @click="visibleUser=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 渲染表格数据 -->
      <el-table  :data="usersList" stripe border>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
          <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
          <el-table-column prop="mg_state" label="状态" width="180">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <!-- 开关按钮 -->
                 <el-switch v-model="scope.row.mg_state" @change="userStatusChang(scope.row)"></el-switch>
              </template>
          </el-table-column>
          <el-table-column  label="操作" width="180">
              <template slot-scope="scope">
                  <!-- 修改用戶 -->
                <el-tooltip content="修改用戶" placement="top" :enterable="false">
                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditFrom(scope.row.id)"></el-button>
                </el-tooltip>
                <!-- 添加用戶 -->
                <el-tooltip content="分配角色" placement="top">
                    <el-button type="warning" size="mini" @click="showRolesDialog(scope.row)"  icon="el-icon-plus" :enterable="false"></el-button>
                </el-tooltip>
                <!-- 刪除用戶 -->
                <el-tooltip content="刪除用戶" placement="top" >
                    <el-button type="danger"  size="mini" @click="deleteUserById(scope.row.id)" icon="el-icon-delete" :enterable="false"></el-button>
                </el-tooltip>
              </template>
          </el-table-column>
      </el-table>
      <!-- 角色分配对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="visivleRoles"
        width="30%"
        >
        <p>当前的用户:{{this.roleinfo.username}}</p>
        <p>当前的角色:{{this.roleinfo.role_name}}</p>
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visivleRoles = false">取 消</el-button>
          <el-button type="primary" @click="defindRolesBtn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加用户提示框 -->
      <el-dialog
              title="提示"
              :visible.sync="visibleUser"
              width="30%"
              @close="dialogClose" >
              <span>添加用户</span>
            <!-- 添加用户表单 -->
            <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px">
                <el-form-item label="添加用户" prop="username">
                  <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="添加密码" prop="password">
                  <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="添加邮箱" prop="email">
                  <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="添加手机号" prop="phone">
                  <el-input v-model="addUserForm.phone"></el-input>
                </el-form-item>
            </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="visibleUser = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
              </span>
            </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="30%"
        @closed="closeEditDialogFrom"
        >
        <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="100px">
          <el-form-item label="用户名"  >
            <el-input v-model="editFrom.username" disabled ></el-input>
          </el-form-item>
           <el-form-item label="邮箱" prop="email" disable >
            <el-input v-model="editFrom.email"></el-input>
          </el-form-item>
           <el-form-item label="手机号" prop="mobile" disable >
            <el-input v-model="editFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页功能 -->
      <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="queryInfo.pagenum"
         :page-sizes="[1, 2, 3, 4]"
         :page-size="queryInfo.pagesize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
    </el-pagination>
    </el-card>

  </div>
</template>

<script>
export default {
  data: function () {
    // 验证自定义邮箱规则
    var checkEmail = (rule, value, callback) => {
      const Email = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (Email.test(value)) {
        return callback()
      }
      callback(new Error('邮箱错误'))
    }
    // 验证自定义手机规则
    var checkPhone = (rule, value, callback) => {
      const Email = /^0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/
      if (Email.test(value)) {
        return callback()
      }
      callback(new Error('手机错误'))
    }
    return {
    // 用户列表参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      usersList: [],
      total: 0,
      visibleUser: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱名称', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]

      },
      editDialogVisible: false,
      // 查询用户表单对象
      editFrom: {},
      // 查询用户表单对象规则
      editFromRules: {
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkPhone, trigger: 'blur' }
        ]

      },
      // 分配角色
      visivleRoles: false,
      // 角色行信息
      roleinfo: {},
      // 角色列表
      rolesList: {},
      value: ''

    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    //   获取用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$Message.error('请求失败')
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 页码大小变动
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 监控开关状态变化
    async userStatusChang (rowData) {
      const { data: res } = await this.$http.put(`users/${rowData.id}/state/${rowData.mg_state}`, rowData.status)
      if (res.meta.status !== 200) {
        rowData.mg_state = !rowData.mg_state
        return this.$Message.error('状态改变失败')
      }
      this.$Message.success('更新成功')
    },
    // 关闭清空表单
    dialogClose () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addUserFormRef.validate(async (value) => {
        if (!value) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$Message.error('添加用户失败')
        this.$Message.success('添加用户成功')
        this.visibleUser = false
        this.getUserList()
      })
    },
    // 展示编辑用户对话框
    async showEditFrom (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return
      this.editFrom = res.data
    },
    // 关闭编辑用户表单
    closeEditDialogFrom () {
      this.$refs.editFromRef.clearValidate()
    },
    editUserInfo () {
      this.$refs.editFromRef.validate(async value => {
        if (!value) return
        const { data: res } = await this.$http.put('users/' + this.editFrom.id, {
          email: this.editFrom.email,
          mobile: this.editFrom.mobile
        })
        if (res.meta.status !== 200) {
          return this.$Message.error('更新用户信息失败')
        }
        this.$Message.success('更新用户信息成功')
        // 更新用户列表
        this.getUserList()
        // 关闭对话框
        this.editDialogVisible = false
      })
    },
    // 删除用户
    async deleteUserById (id) {
      const str = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 确认了删除返回confirm
      // 取消了删除返回cancel

      if (str !== 'confirm') {
        return this.$Message.Info('取消删除成功')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$Message.error('删除用户失败')
      this.$Message.success('删除用户成功')
      this.getUserList()
    },
    // 监听分配角色对话框
    async showRolesDialog (roleinfo) {
      this.visivleRoles = true
      this.roleinfo = roleinfo
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    // 确定角色按钮
    async defindRolesBtn () {
      console.log(this.roleinfo.id, this.rolesID)
      const { data: res } = await this.$http.put(`roles/${this.roleinfo.id}/rights`, { rids: this.rolesID })
      if (res.meta.status !== 200) this.$Message.error('分配失败')
    }

  }
}
</script>

<style lang="less" scoped>
</style>
